<template>
  <div class="changePassword">
    <el-dialog
      v-model="dialogVisible"
      title="重置密码"
      width="650px"
      @closed="closed"
    >
      <div class="dialog-content">
        <el-form
          ref="ruleFormRef"
          :model="ruleForm"
          :rules="rules"
          label-width="80px"
          class="demo-ruleForm"
          status-icon
        >
          <el-form-item label="新密码" prop="newPassword">
            <el-input v-model.trim="ruleForm.newPassword" type="password" />
          </el-form-item>
          <el-form-item label="确认密码" prop="assignPassword">
            <el-input v-model.trim="ruleForm.assignPassword" type="password" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submit" :loading="isLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { computed } from "vue";
import { ElMessage, FormInstance, FormRules } from "element-plus";
import { reactive } from "vue";
import { resetPassword } from "@/api/system";
defineOptions({
  name: "changePassword"
});
interface Props {
  modelValue: boolean;
  userId: number;
}
const props = defineProps<Props>();
const emits = defineEmits(["update:modelValue"]);
const dialogVisible = computed({
  get() {
    return props.modelValue;
  },
  set(newValue) {
    emits("update:modelValue", newValue);
  }
});
// 表单
const ruleFormRef = ref<FormInstance>();
const ruleForm = ref({
  newPassword: "",
  assignPassword: ""
});
// 表单验证规则
// 两次密码是否一致
const validateAssignPassword = (rule: any, value: any, callback: any) => {
  if (ruleForm.value.newPassword !== ruleForm.value.assignPassword) {
    callback(new Error("两次密码不一致"));
  } else {
    callback();
  }
};
const rules = reactive<FormRules<typeof ruleForm>>({
  newPassword: [{ required: true, message: "请输入密码", trigger: "blur" }],
  assignPassword: [
    { required: true, message: "请输入密码", trigger: "blur" },
    {
      validator: validateAssignPassword,
      trigger: "blur"
    }
  ]
});
// 提交
const isLoading = ref(false);
const submit = () => {
  ruleFormRef.value.validate(async valida => {
    if (valida) {
      isLoading.value = true;
      const res = await resetPassword({
        userId: props.userId,
        password: ruleForm.value.newPassword
      });
      isLoading.value = false;
      if (res.code === 200) {
        dialogVisible.value = false;
        ElMessage.success("密码重置成功");
      }
    }
  });
};
const closed = () => {
  ruleFormRef.value.resetFields();
};
</script>
